package com.papper.mng.controller.log;

import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import com.papper.common.bean.log.LogException;
import com.papper.common.bean.log.LogInterface;
import com.papper.common.constant.SystemConstants;
import com.papper.common.service.DwzPage;
import com.papper.common.service.log.LogInterfaceService;
import com.papper.common.utils.tool.DateTool;
import com.papper.common.utils.tool.StringTool;
import com.papper.mng.controller.BaseAction;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

/**
 * @Author:LaJiao
 * @Date:2016-08-12 13:55:37
 * @Description:接口请求日志
 */
@Controller
@RequestMapping("/log/interface")
public class LogInterfaceAction extends BaseAction {
	@Resource
	LogInterfaceService logInterfaceService;

	/**
	 * 接口请求日志
	 *
	 * @return
	 */
	@GetMapping(value = "")
	public String execute(HttpServletRequest _request, HttpServletResponse _response, Model model) {
		// 字段查询条件
		Map<String, Object> objects = Maps.newHashMap();
		extraParams(objects, _request, LogInterface.class);
		String ts = _request.getParameter("ts");
		if (StringTool.isEmpty(ts)) {
			ts = DateTool.formatDate(DateTool.addMins(new Date(), -120), DateTool.FULL_TRADITION_PATTERN);
		}
		objects.put("ts", ts);
		String te = _request.getParameter("te");
		if (StringTool.isEmpty(te)) {
			te = DateTool.getDayEnd();
		}
		objects.put("te", te);
		modelParm(objects, model);
		// 分页查询条件
		int pageNum    = StringTool.parseInteger(_request.getParameter("pageNum"), 1);
		int numPerPage = StringTool.parseInteger(_request.getParameter("numPerPage"), SystemConstants.PAGE_LIMIT_16);
		// 数据查询组装
		Example example = buildExample(objects, model, LogException.class);
		if (!StringTool.isEmpty(objects.get("searchValue"))) {
			Example.Criteria criteria = example.createCriteria();
			criteria.andLike("loggerContent", "%" + objects.get("searchValue") + "%");
			example.and(criteria);
		}
		PageInfo<LogInterface> pageRtn = logInterfaceService.findPage(pageNum, numPerPage, example);
		model.addAttribute("page", new DwzPage(pageNum, numPerPage, pageRtn.getTotal()));
		model.addAttribute("records", pageRtn.getList());
		return render("log/interface/index");
	}

	/**
	 * 接口请求日志_详情
	 *
	 * @return
	 */
	@GetMapping(value = "/detail")
	public String detail(HttpServletResponse _response, Model model, Long id) throws IOException {
		LogInterface logInterface = logInterfaceService.findById(id);
		model.addAttribute("entity", logInterface);
		return render("log/interface/detail");
	}
}